<template>
  <div class="applicationReminderContainer">
    <el-card class="box-card"
             shadow="never">
      <div slot="header"
           class="clearfix">
        <div style="font-weight: 700; font-size: 19px">佣金账单</div>
        <div class="selectTime">
          <ul class="timeTab"
              v-for="(item, index) in options"
              :key="index">
            <li :class="[currentIndex == index ? 'active' : '']"
                @click="switchTimeTab(index)">{{ item.value }}</li>
          </ul>

          <div class="filterDate">筛选日期</div>
          <el-date-picker v-model="sumbitForm.selectDateRange"
                          type="datetimerange"
                          unlink-panels
                          @change="dataTimePickFn"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          class="ele-fluid" />
        </div>
      </div>
      <div class="applicationInfo">
        <div class="Divider">
          <span>总佣金</span>
          <div>{{
            commissionBillInfo.totalBrokerage
              ? commissionBillInfo.totalBrokerage
              : '0'
          }}</div>
        </div>
        <div class="Divider">
          <span>待结算</span>
          <div>{{ commissionBillInfo.toBeSettled?commissionBillInfo.toBeSettled:'0' }}</div>
          <div style="font-size: 14px; color: #757575">待结算<span style="color: #ff4d4f; font-size: 14px">
              {{
                commissionBillInfo.toBeSettledCount
                  ? commissionBillInfo.toBeSettledCount
                  : '0'
              }}笔</span></div>
        </div>
        <div style="border-right: none"
             class="Divider">
          <span>已结算</span>
          <div>{{
            commissionBillInfo.haveAlreadySettled
              ? commissionBillInfo.haveAlreadySettled
              : '0'
          }}</div>
          <div style="font-size: 14px; color: #757575">已结算<span style="color: #ff4d4f; font-size: 14px">
              {{
                commissionBillInfo.haveAlreadySettledCount
                  ? commissionBillInfo.haveAlreadySettledCount
                  : '0'
              }}笔</span></div>
        </div>
      </div>
    </el-card>
    <el-card class="card"
             shadow="never">
      <UserSearch @search="reload"
                  :currentPlatform="currentPlatform"
                  :oemList="oemList"
                  :secondaryList="secondaryList"></UserSearch>
    </el-card>
    <el-card shadow="never">
      <ele-pro-table ref="table"
                     :datasource="datasource"
                     :columns="columns"
                     :selection.sync="selection"
                     cache-key="systemUserTable">
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <!-- <div class="flex-align-center">
            <div v-for="(i, j) in stautsList"
                 :key="j"
                 @click="stautsClick(j)"
                 :class="stautsIndex == j ? 'sel-stauts-class' : 'stauts-class'">{{ i.name }}</div>
          </div> -->
        </template>
        <template v-slot:tradeType="{ row }">
          <el-tag :type="row.tradeType == 'NATIVE' ? 'success' : ''">
            {{ tradeTypeC(row.tradeType).status }}
          </el-tag>

        </template>
        <template v-slot:auditDate="{ row }">
          <div class="font-overflow">{{ row.auditDate?row.auditDate:'--'}}</div>
        </template>
        <template v-slot:totalBrokerage="{ row }">
          <div class="font-overflow">{{ row.totalBrokerage?row.totalBrokerage:'--'}}</div>
        </template>
        <template v-slot:transactionId="{ row }">
          <div class="font-overflow">{{ row.transactionId?row.transactionId:'--'}}</div>
        </template>
        <!-- 用户名列 -->
        <template v-slot:withdrawStatus="{ row }">
          <el-tag :type="row.withdrawStatus == '1' ? 'success' : ''">
            {{ applyForType(row.withdrawStatus) }}
          </el-tag>
        </template>

        <!-- 状态列 -->
        <template v-slot:status="{ row }">
          <el-switch :active-value="2"
                     :inactive-value="1"
                     v-model="row.status"
                     @change="editStatus(row)" />
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-popconfirm class="ele-action"
                         title="是否确定要删除该笔佣金账单信息"
                         @confirm="remove(row)">
            <template v-slot:reference>
              <el-link type="danger"
                       :underline="false"
                       icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
  </div>
</template>
<script>
import { oemAgentQuery } from '@/api/oem';
import {
  getCommissionBill,
  getCommissionBillList,
  getWxbrokerageorderList
} from '@/api/commissionManagement';
import moment from 'moment';
import UserSearch from './components/user-search.vue';
export default {
  name: 'commissionBill',
  components: {
    UserSearch
  },
  data () {
    this.currentPlatformFn()
    return {
      // 全部状态数量
      allStatusNumber: 5,
      // 已经支付
      paidNumber: 119,
      //  未支付
      unPaid: 15,
      // 当天时间的实例
      currentMoment: null,
      labelPosition: 'top',
      // 当前索引
      currentIndex: 1,
      selection: [],
      secondaryList: [],
      oemList: [],
      //   头像查询信息
      commissionBillInfo: {},
      //   当前所在平台
      currentPlatform: '',
      billList: [],
      options: [
        {
          value: '昨天'
        },
        {
          value: '今天'
        },
        {
          value: '前天'
        },
        {
          value: '近七天'
        }
      ],
      stautsIndex: '',
      withdrawStatusIndex: '',
      //  当前状态
      //  状态配置
      stautsList: [
        {
          name: '全部状态',
          id: ''
        },
        {
          name: '线上支付',
          id: 0
        },
        {
          name: '线下支付',
          id: 1
        }
      ],
      sumbitForm: {
        selectDateRange: []
      },
      // 表格列配置
      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: 'left',
          sortable: true
        },
        {
          columnKey: 'index',
          type: 'index',
          label: '序号',
          width: 60,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'merchantName',
          //   prop: 'MerchantName',
          label: '商家名称',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 90,
          sortable: true,
          align: 'center',
        },

        {
          prop: this.currentPlatform == '总平台' ? 'total' :
            'payAmount',
          label: '订单金额',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,
          sortable: true,
          align: 'center',
        },

        {
          prop: this.currentPlatform == '总平台' ? 'totalBrokerage' :
            'forecastBrokerage',
          label: '预估佣金',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,
          sortable: true,
          align: 'center',
          slot: this.currentPlatform == '总平台' ? 'totalBrokerage' : 'forecastBrokerage',
        },
        {
          prop: 'parentCode',
          label: 'OEM代理',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 90,
          sortable: true,
          align: 'center',
        },
        // {
        //   prop: 'tradeType',
        //   label: '交易类型',
        //   sortable: 'custom',
        //   showOverflowTooltip: true,
        //   minWidth: 110,
        //   sortable: true,
        //   slot: 'tradeType',
        //   align: 'center',
        // },
        {
          prop: 'oemCode',
          label: '下属代理',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 90,
          sortable: true,
          align: 'center',
        },
        {
          prop: 'transactionId',
          label: '订单编号',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 170,
          sortable: true,
          align: 'center',
          slot: 'transactionId',
        },

        {
          prop: 'createDate',
          label: '申请时间',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 100,
          sortable: true,
          align: 'center',
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 180,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: true,
          fixed: 'right',
          sortable: true
        }
      ],
      stautsIndex: 0,
      withdrawStatusIndex: null
    };
  },
  // 路由刷新
  activated () {
    this.currentPlatformFn()
    this.switchTimeTab(this.currentIndex);
    this.queryOem();
    this.querySecondary();
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    },
    applyForType () {
      return function (applyType) {
        // console.log(applyType)
        if (applyType == '1') {
          return '已结算';
        } else {
          return '待结算';
        }
      };
    },
    // 交易类型
    tradeTypeC () {
      return function (tradeType) {
        if (tradeType == 'NATIVE') {
          return {
            status: '线下支付',
            type: ''
          };
        } else {
          return {
            status: '线上支付',
            type: 'danger'
          };
        }
      };
    },
  },

  methods: {

    // 判断什么平台
    currentPlatformFn () {
      if (
        this.$store.state.user.info.oemId == null &&
        this.$store.state.user.info.merchantId == null
      ) {
        console.log('总平台');
        this.currentPlatform = '总平台';
      } else if (
        this.$store.state.user.info.oemId !== null &&
        this.$store.state.user.info.merchantId == null
      ) {
        console.log('oem代理');
        this.currentPlatform = 'oem代理';
      } else {
        console.log('商家端');
        this.currentPlatform = '商家端';
      }
    },
    // 查询确定
    dataTimePickFn (timeArr) {
      this.init(timeArr[0], timeArr[1]);
      this.currentIndex = 100;
    },
    async init (startTime = '', endTime = '') {
      const res = await getCommissionBill({
        startTime,
        endTime,
        oemId: this.$store.state.user.info.oemId
          ? this.$store.state.user.info.oemId
          : ''
      });
      console.log(res);
      if (res.code == 2000) {
        this.commissionBillInfo = res.data;
      } else {
        this.$message.error(res.msg);
      }
    },
    stautsClick (index) {
      if (index == 0) {
        this.stautsIndex = index;

        this.reload({ tradeType: '' });
      } else if (index == 1) {
        this.stautsIndex = index;

        this.reload({ tradeType: 'MWEB' });
      } else {
        this.stautsIndex = index
        this.reload({ tradeType: 'NATIVE' })
      }
    },
    switchTimeTab (index) {
      this.sumbitForm.selectDateRange = [];
      this.currentIndex = index;
      this.currentMoment = moment();

      console.log(index);

      if (index == 0) {
        // 获取当前日期时间
        this.currentMoment.startOf('day');

        const currentDate = this.currentMoment.format('YYYY-MM-DD HH:mm:ss');
        console.log(currentDate);
        // 减去一天的时间
        const previousDate = this.currentMoment.subtract(1, 'days');

        // 格式化为指定的字符串格式（YYYY-MM-DD HH:mm:ss）
        const formattedDate = previousDate.format('YYYY-MM-DD HH:mm:ss');
        console.log(formattedDate);

        this.init(currentDate, formattedDate);
      } else if (index == 1) {
        // 获取当前日期时间
        this.currentMoment.startOf('day');
        const currentDate = this.currentMoment.format('YYYY-MM-DD HH:mm:ss');
        console.log(currentDate);

        const previousDate = this.currentMoment.add(1, 'days');

        const formattedDate = previousDate.format('YYYY-MM-DD HH:mm:ss');
        console.log(formattedDate);
        this.init(currentDate, formattedDate);
      } else if (index == 2) {
        // 获取当前日期时间
        this.currentMoment.startOf('day');
        const currentDate = this.currentMoment.format('YYYY-MM-DD HH:mm:ss');
        console.log(currentDate);

        const previousDate = this.currentMoment.subtract(2, 'days');

        const formattedDate = previousDate.format('YYYY-MM-DD HH:mm:ss');
        console.log(formattedDate);
        this.init(currentDate, formattedDate);
      } else if (index == 3) {

        const currentDate = this.currentMoment.format('YYYY-MM-DD HH:mm:ss');
        console.log(currentDate);
        // 减去一天的时间
        this.currentMoment.startOf('day');
        const previousDate = this.currentMoment.subtract(7, 'days');

        // 格式化为指定的字符串格式（YYYY-MM-DD HH:mm:ss）
        const formattedDate = previousDate.format('YYYY-MM-DD HH:mm:ss');
        console.log(formattedDate);
        this.init(formattedDate, currentDate);
      }
    },
    async datasource ({ page, limit, where, order }) {
      //   console.log(where, order);
      //   if (!where.deleted) where.deleted = 0;
      this.currentPlatformFn()
      this.billList = await (this.currentPlatform === '总平台' ? getCommissionBillList : getWxbrokerageorderList)({
        ...where,
        ...order,
        page,
        limit,
        [this.currentPlatform === '总平台' ? 'oemId' : 'agentId']: this.$store.state.user.info.oemId
          ? this.$store.state.user.info.oemId
          : ''
      });
      return this.billList
    },
    // 查询所有代理
    queryOem () {
      oemAgentQuery({
        limit: 10,
        oemType: 1,
        page: 1,
        types: 1
      })
        .then((data) => {
          console.log('data===', data.list);
          this.oemList = data.list;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    // 查询所有二级代理
    querySecondary () {
      oemAgentQuery({
        limit: 10,
        oemType: 2,
        page: 1,
        types: 2,
        parentId: this.currentPlatform == 'oem代理' ? this.$store.state.user.info.oemId : ''
      })
        .then((data) => {
          console.log('data===', data.list);
          this.secondaryList = data.list;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    reload (where) {
      console.log('where', where);
      //
      if (this.withdrawStatusIndex == 0 || this.withdrawStatusIndex == 1) {
        // 判断 where里面有没有 withdrawStatus 字段 如果有就放行 没有就添加
        if ('withdrawStatus' in where) {
          console.log('存在 withdrawStatus 属性');
          this.$refs.table.reload({ where: where });
          return;
        } else {
          console.log('不存在');
          let data = {
            ...where,
            ...{ withdrawStatus: this.withdrawStatusIndex }
          };
          this.$refs.table.reload({ where: data });
          return;
        }
      }

      this.$refs.table.reload({ where: where });
    },
    /* 批量删除 */
    removeBatch () {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.$confirm('确定要删除选中的代理吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({ lock: true });
          removeUsers({ ids: this.selection.map((d) => d.id) })
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        })
        .catch(() => { });
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ele-table-tool-default {
  margin-bottom: -5px;
  padding: 0;
}
/* 单行文字省略 */
.font-overflow {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
.applicationReminderContainer {
  min-width: 400px;
  .box-card {
    .clearfix {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0px 0 0 20px;
      min-width: 960px;
      .selectTime {
        display: flex;
        align-items: center;
        .timeTab {
          display: flex;
          align-items: center;
          margin-right: 20px;
          li {
            list-style-type: none;
            display: block;
            width: 48px;
            text-align: center;
          }
          .active {
            width: 64px;
            height: 26px;
            border-radius: 6px;
            background: #1890ff;
            color: #fff;
            text-align: center;
            line-height: 26px;
          }
        }
        .filterDate {
          text-align: center;
          line-height: 34px;
          width: 90px;
          height: 34px;
          font-size: 14px;
          border-radius: 2px 0px 0px 2px;
          border: 1px solid #d9d9d9;
          border-right: none;
        }
        .ele-fluid {
          width: 300px !important;
        }
      }
    }
  }
  .stauts-class,
  .sel-stauts-class {
    font-size: 14px;
    margin: 0 26px 0 26px;
    padding: 9px 0px 9px;
    line-height: 19px;
  }
  .stauts-class {
    color: #757575;
  }
  .sel-stauts-class {
    color: #1e6ceb;
    border-bottom: 2px solid #1e6ceb;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
  }
  .applicationInfo {
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      color: #757575;
      font-size: 18px;
    }

    .Divider {
      text-align: center;
      width: 30%;
      height: 90px;
      border-right: 1px solid #ebebeb;
    }

    div {
      margin: 3px 0 3px 0;
      color: #1e6ceb;

      font-size: 28px;
    }
  }
  .settlementStatus {
    display: flex;
    .allStatus {
      color: #000;
      margin-right: 47px;
    }
    .noSettlement {
      color: #666;
      margin-right: 47px;
    }
    .settlementSuccess {
      color: #666;
      margin-right: 47px;
    }
  }
}
</style>
